package com.kangdi.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.kangdi.server.config.component.JwtTokenUtil;
import com.kangdi.server.mapper.AdminMapper;
import com.kangdi.server.mapper.RoleMapper;
import com.kangdi.server.pojo.Admin;
import com.kangdi.server.pojo.AdminRole;
import com.kangdi.server.pojo.RespBean;
import com.kangdi.server.pojo.Role;
import com.kangdi.server.service.IAdminRoleService;
import com.kangdi.server.service.IAdminService;
import com.kangdi.server.util.AdminUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * InnoDB free: 7168 kB 服务实现类
 * </p>
 *
 * @author kangdi
 * @since 2022-10-04
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private IAdminRoleService adminRoleService;

    @Override
    public RespBean login(String username, String password,String code, HttpServletRequest request) {
        String captcha= (String) request.getSession().getAttribute("captcha");
        if(StringUtils.isEmpty(code)||!code.equalsIgnoreCase(captcha)){
            return RespBean.error("验证码有无，请重新输入验证码");
        }
        //登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (userDetails==null||!passwordEncoder.matches(password,userDetails.getPassword())){
            return RespBean.error("用户名或密码为空");
        }
        if (!userDetails.isEnabled()){
            return RespBean.error("账号已被禁用");
        }
        //更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //生成Token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String,String> tokenMap=new HashMap<String,String>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);
        return RespBean.success("登陆成功",tokenMap);
    }

    @Override
    public Admin getAdminByUsername(String username) {
         return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",username).eq("enabled",true));
    }

    @Override
    public List<Role> getRoles(Integer adminId) {
        return roleMapper.getRoles(adminId);
    }

    /**
     * 获得管理员信息
     * @param keyWord
     * @return
     */
    @Override
    public List<Admin> getAllAdmins(String keyWord) {
        return adminMapper.getAllAdmins(AdminUtil.getAdmin().getId(),keyWord);
    }
    /**
     * 更新操作员的角色信息
     * @param adminId
     * @param roles
     * @return
     */
    @Override
    @Transactional
    public RespBean updateAdminRole(Integer adminId, Integer[] roles) {
        adminRoleService.remove(new QueryWrapper<AdminRole>().eq("adminId",adminId));
        if (roles==null||roles.length<0){
            return RespBean.success("更新成功");
        }
        int result= adminRoleService.addRoles(adminId,roles);
        if (result==roles.length){
            return RespBean.success("更新成功");
        }
        return RespBean.error("更新失败");
    }

    /**
     * 更新密码
     * @param oldPass
     * @param pass
     * @param adminId
     * @return
     */
    @Override
    public RespBean updateAdminPassword(String oldPass, String pass, Integer adminId) {
        Admin admin = adminMapper.selectById(adminId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (encoder.matches(oldPass,admin.getPassword())){
            admin.setPassword(encoder.encode(pass));
            int result = adminMapper.updateById(admin);
            if (result==1){
                return RespBean.success("更新成功");
            }
        }
        return RespBean.error("更新失败");
    }
}
